<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\User;
use App\Model\Trading_stream;

class UserController extends Controller
{
    private $user;

    function __construct(User $user)
    {
        $this->user = $user;
    }

    public function recharge(Request $request)
    {
        $post = $request->input();

        if (empty($post) || count($post) == 0) {
            return return_array(1, "非法操作");
        }

        $user = get_session_user();
        if (empty($user))
            return return_array(1, "非法用户");
        //开启事务
        $this->user->trans_begin();
        $this->user = $this->user->find($user["user_id"]);
        $this->user->balance += $post["balance"];
        if (!$this->user->save()) {
            $this->user->trans_rollback();
            return return_message(1, "失败");
        }
        session(array("user_info" => $this->user->toArray()));

        $tsModel = new Trading_stream();
        $type = config('bar.trading_stream.type');
        $data = array(
            "user_id" => $user["user_id"],
            "change" => $post["balance"],
            "info" => $type[0][1],
            "type" => $type[0][0],
        );
        if (!$tsModel->add_trading_stream($data)) {
            $this->user->trans_rollback();
            return return_message(1, "失败");
        }

        $this->user->trans_commit();
        return return_message(0, "OK");
    }
}
